﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/easyui/themes/black/easyui.css?t564">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/easyui/themes/color.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/farm/farm.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/farm/imgPosition.css?t=0901">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>ext/seed/grid.css">
    <script type="text/javascript" src="<%=basePath%>ext/farm/utils.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/easyui/plugins/jquery.edatagrid.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/easyui/plugins/jquery.draggable.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="<%=basePath%>ext/farm/imgPosition.js"></script>
</head>
<style type="text/css">
	body, html{
		width: 100%; 
		height: 100%; 
		background-image: url(<%=basePath%>/images/backgroundImg.png);
	}
</style>
<body>
	<div id="controlBox">
	    <a href="#" class="easyui-linkbutton c2" iconCls="icon-add" onclick="addCropsCrowInfo()">添加</a>
	    <a href="#" class="easyui-linkbutton c4" iconCls="icon-edit" onclick="loadForm()">编辑</a>
	    <!-- <a href="#" class="easyui-linkbutton c2" iconCls="icon-add" onclick="javascript:$('#editCropsGrowData').dialog('addRow')">添加</a>
	    <a href="#" class="easyui-linkbutton c4" iconCls="icon-edit" onclick="javascript:$('#editCropsGrowData').dialog('editRow')">编辑</a> -->
	    
	    <a href="#" class="easyui-linkbutton c3" iconCls="icon-remove" onclick="javascript:$('#editCropsGrowData').dialog('close')">取消</a>
	    <a href="#" class="easyui-linkbutton c5" iconCls="icon-cancel" onclick="javascript:grid.edatagrid('destroyRow')">删除</a>
	</div>
	<table id="grid" style="width: 100%;"></table>
	<div id="msgBox"></div>
	
	<div id="editCropsGrowData" class="easyui-window" buttons="#editCropsGrowButtons" title="编辑数据" 
		data-options="iconCls:'icon-edit', closed: true" style="width: 70%; height:310px; padding: 5px;">
		<form id="formEditCropsGrow" novalidate>
			<table id="editCropsGrowTable">
				<tr>
					<td class="wideTd">ID:</td>
					<td class="inputTd"><input id="ID" name="id" value="0" readonly="readonly"/></td>
					<td class="narrowTd"></td>
					<td class="wideTd">种子ID:</td>
					<td class="inputTd"><input id="seedId" name="seedId" value="${seedId}" readonly="readonly"/>
					</td>
					<td class="narrowTd"></td>
				</tr>
				<tr>
					<td class="wideTd">生长阶段:</td>
					<td class="inputTd"><input id="stageImage" name="stageImage" class="easyui-numberbox"
						data-options="
							required:true,
							validType:'length[0,1]',
							invalidMessage: '请输入0~9'"/></td>
					<td class="narrowTd"></td>
					<td class="wideTd">生长阶段标题:</td>
					<td class="inputTd"><input name="stageTitle" class="easyui-textbox" 
						data-options="
							required:true,
							validType:'length[1, 5]',
							invalidMessage: '有效长度1-5'"/>
					</td>
					<td class="narrowTd"></td>
				</tr>
				<tr>
					<td class="wideTd">阶段生长时间:</td>
					<td class="inputTd"><input name="stageTime" class="easyui-numberbox"
						data-options="
								required:true,
								validType:'length[1,50]',
								invalidMessage: '有效长度1-50'"/>
					</td>
					<td class="narrowTd">秒</td>
					<td class="wideTd">生虫概率:</td>
					<td class="inputTd"><input name="insectProb" class="easyui-numberbox"
						data-options="
								required:true,
								precision: 1,
								validType:'length[1,3]',
								max: 1,
								invalidMessage: '请输入0~1之间的小数'"/>
	                </td>
					<td class="narrowTd"></td>
				</tr>
				<tr>
					<td class="wideTd">图片宽度:</td>
					<td class="inputTd"><input id="imgWidth" name="imgWidth" readonly="readonly" class="easyui-numberbox"/>
					</td>
					<td class="narrowTd">px</td>
					<td class="wideTd">图片高度:</td>
					<td class="inputTd"><input id="imgHeight" name="imgHeight" readonly="readonly" class="easyui-numberbox"/>
					</td>
					<td class="narrowTd">px</td>
				</tr>
				<tr>
					<td class="wideTd">图片offsetX:</td>
					<td class="inputTd"><input id="offsetX" name="offsetX" readonly="readonly" class="easyui-numberbox"/>
					</td>
					<td class="narrowTd">px</td>
					<td class="wideTd">图片offsetY:</td>
					<td class="inputTd"><input id="offsetY" name="offsetY" readonly="readonly" class="easyui-numberbox"/>
					</td>
					<td class="narrowTd">px</td>
				</tr>
				<tr>
					<td class="wideTd">作物状态:</td>
					<td class="inputTd"><input name="cropStatus" class="easyui-combobox" panelHeight="auto"
						data-options="editable:false,
	                                    valueField:'code',
	                                    textField:'caption',
	                                    required:true,
	                                    url:'<%=basePath%>/cropsStatus/data'"/>
					</td>
					<td class="narrowTd"></td>
					<td class="wideTd"></td>
					<td class="inputTd"><input onclick="showImgEditBox()" type="button" value="编辑图片位置" /></td>
					<td class="narrowTd"></td>
				</tr>
			</table>
		</form>
		<div id="editCropsGrowButtons" style="margin-top: 1%">
    		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" style="margin-left: 40%" onclick="saveCropsGrowForm()">保存</a>
    		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#editCropsGrowData').dialog('close')">取消</a>
		</div>
	</div>
	
	
	<!-- 图片编辑器 -->
	<div id="positionDialog" class="easyui-dialog" title="图片编辑器"  style="width:240px; height:420px; padding:10px 10px" 
		closed="true" buttons="#positionDialogButtons">
		<div id="tools-imagePositioner-display" class="tools-imagePositioner-display">
       		<img id="editImgBox" class="easyui-draggable easyui-resizable" data-options="onDrag:imagePositioneronDrag">
    	</div>
	</div>
	<div id="positionDialogButtons">
	    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" 
	    	onclick="gainPostion()">确定</a>
	    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" 
	    	onclick="javascript:$('#positionDialog').dialog('close')">取消</a>
    </div>
	
	<script type="text/javascript">
		// 获取cropStatus的所有类型
		var cropStatusObject;
		$(function(){
	    	var url = '<%=basePath%>/cropsStatus/data';
	    	getRemoteData(url, getCropStatusObject);
	    })
	    function getCropStatusObject(data){
	    	cropStatusObject = data;
	    }
		
		var params = {
	        id: '',
	        mode: 'insert'
	    };
	    var high = window.innerHeight - 45;
	    var grid;
	    $(document).ready(function () {
	        //配置表格
	        grid = $('#grid').edatagrid({
	            title: '成长阶段',
	            method: 'post',
	            height: high,
	            /* height: getHeight(),  */
	            url: '<%=basePath%>/cropsGrow/list?seedId=' + '${seedId}',
	            <%-- saveUrl: '<%=basePath%>/seed/save', --%>
	            updateUrl: '<%=basePath%>/cropsGrow/save',
	            destroyUrl: '<%=basePath%>/cropsGrow/delete',
	            border: false,
	            rownumbers: true,  // 设置为true，则显示带有行号的列
	            remoteSort: true,  // 定义是否从服务器排序数据
	            nowrap: false,  // 设置为true，则把数据显示在一行里。设置为true能提高加载性能
	            singleSelect: true,  // 设置为true，则只允许选中一行
	            fitColumns: true,  // 使列自动展开/折叠以适应数据网格（datagrid）的宽度
	            
	            /* pagination: true,  // 设置为true，则在数据网格（datagrid）底部显示分页工具 */
	            striped: true,  // 设置为true，则把行条纹化。（即奇偶行使用不同背景色）
	            autoSave: true,  // 自动保存
	            idField: "id",
	            columns:[[
		        	{field: 'id', title: "ID", width: 60, align: 'center', halign: 'center'},
		        	{field: 'seedId', title: "种子ID", width: 60, align: 'center', halign: 'center'},
		        	{field: 'stageImage', title: "生长阶段", width: 60, align: 'center', halign: 'center',
		        		sortable: true,
		        		editor: {
	                        type: 'numberbox',
	                        options: {
	                            validType: 'length[0,1]',
	                            invalidMessage: '请输入0~9',
	                            required: true
	                        }
	                    }	
		        	},
		        	{field: 'stageTitle', title: "生长阶段标题", width: 80, align: 'center', halign: 'center',
		        		sortable: true,
		        		editor: {
		        			type: 'textbox',
		        			options: {
		        				required:true,
								validType:'length[1,50]',
								invalidMessage: '有效长度1-50'
		        			}
		        		}
		        	},
		        	{field: 'stageTime', title: "阶段生长时间", width: 80, align: 'center', halign: 'center',
		        		sortable: true,	
		        		editor: {
		        			type: 'numberbox',
		        			options: {
		        				required:true,
								validType:'length[1,50]',
								invalidMessage: '有效长度1-50'
		        			}
		        		}
		        	},
		        	{field: 'insectProb', title: "生虫概率", width: 60, align: 'center', halign: 'center',
		        		sortable: true,
		        		editor: {
		        			type: 'numberbox',
		        			options: {
		        				required:true,
								precision: 1,
								validType:'length[1,3]',
								max: 1,
								invalidMessage: '请输入0~1之间的小数'
		        			}
		        		}
		        	},
		        	{field: 'imgWidth', title: "图片宽度", width: 60, align: 'center', halign: 'center',
		        		sortable: true,	
		        	},
		        	{field: 'imgHeight', title: "图片高度", width: 80, align: 'center', halign: 'center',
		        		sortable: true,	
		        	},
		        	{field: 'offsetX', title: "图片offsetX", width: 80, align: 'center', halign: 'center',
		        		sortable: true,	
		        	},
		        	{field: 'offsetY', title: "图片offsetY", width: 80, align: 'center', halign: 'center',
		        		sortable: true,	
		        	},
		        	{field: 'cropStatus', title: "作物状态", width: 60, align: 'center', halign: 'center',
		        		sortable: true,
		        		editor: {
		        			type: 'combobox',
		        			options: {
		        				editable:false,
                                valueField:'code',
                                textField:'caption',
                                data: cropStatusObject,
                                panelHeight: 'auto',
		        			}
		        		},
		        		formatter: function (value, row) {
		        			return cropStatusObject[row.cropStatus].caption;
	                    }
		        			
		        	},
		        ]],
		        
	            destroyMsg: {
	                norecord: {
	                    title: '警告',
	                    msg: '首先需要选中记录，然后在点击删除按钮'
	                },
	                confirm: {
	                    title: '确认',
	                    msg: '是否删除选中记录?'
	                }
	            },
	            onSuccess: function (index, result) {
	                $("#msgBox").text(result.msg);
	            },
	            onDestroy: function (index, result) {
	                console(result);
	                $("#msgBox").text(result.msg);
	            }
	        });
	        /* grid.datagrid("getPager").pagination({
	            pageSize: 5,
	            pageList: [5, 10, 15, 20]
	        }); */
	    });
	    
	 	// 编辑数据
	    function loadForm() {
	        var row = grid.datagrid('getSelected');
	       	/* console.log(row); */
	        if (row) {
	            params.id = row.id;
	            params.mode = 'edit';
	            $('#editCropsGrowData').dialog('open').dialog('setTitle', '编辑数据');
	            $('#editCropsGrowData').dialog('open').dialog('open');
	            $('#formEditCropsGrow').form('load', row);
	        } else {
	            alert("请先选择一行数据，然后再尝试点击操作按钮！");
	        }
	    }
	    
	 	// 添加
	 	function addCropsCrowInfo(){
	 		$("#grid").datagrid('clearSelections');
	 		$('#editCropsGrowData').dialog('open');
	 		$('#formEditCropsGrow').form('clear');
	        $('#formEditCropsGrow').find("input[name='id']").val(0);
	        $('#formEditCropsGrow').find("input[name='seedId']").val("${seedId}");
	 	}
	 	
	 	/* function clearTable(){
	 		var row = {};
		 	row.id = 0;
		 	row.seedId = "${seedId}";
		 	row.stageImage = "";
		 	row.stageTitle = "";
		 	row.stageTime = "";
		 	row.insectProb = "";
		 	row.imgWidth = "";
		 	row.imgHeight = "";
		 	row.offsetX = "";
		 	row.offsetY = "";
		 	row.cropStatus = "";
	 		return row;
	 	} */
	 	
		// 保存
	    function saveCropsGrowForm() {
	    	$('#formEditCropsGrow').form('submit', {
	            url: '<%=basePath%>/cropsGrow/save',
	            onSubmit: function (param) {
	            	/* console.log(param); */
	                return $(this).form('validate');
	            },
	            success: function (result) {
	            	console.log(result);
	                var result = eval('(' + result + ')');  // eval本质就是执行一段代码。如果result是一个文本，那就可以通过这种方式转换为对象
	                console.log(result);
	                if (result.code == 0) {
	                    $('#editCropsGrowData').dialog('close');
	                    grid.datagrid('reload');
	                }
	                $.messager.show({
	                    title: "消息",
	                    msg: result.msg
	                });
	            }
	        });
	    }
	    
	    /* 编辑和获取图片位置信息 */
		function showImgEditBox(){
			var seedId = document.getElementById("seedId");
			var stageImage = document.getElementById("stageImage");
			if(stageImage.value == ""){
				alert("请输入生长阶段");
				return;
			}
			var editImgBox = document.getElementById("editImgBox");
			if(parseInt(stageImage.value) >= 0 && parseInt(stageImage.value) <= 5){
				editImgBox.src = "<%=basePath%>/images/crops/" + seedId.value + "/" + stageImage.value + ".png";
			}else{
				editImgBox.src = "<%=basePath%>/images/crops/" + seedId.value + "/9.png";
			}
			$('#positionDialog').dialog('open');
			
			// 初始化图片位置
			draggableImg = $('#tools-imagePositioner-display img');
			/* console.log("图片1");
			console.log(draggableImg); */
			positionerLoadImage();
			var offsetX = $('#formEditCropsGrow').find("input[name='offsetX']").val();
			var offsetY = $('#formEditCropsGrow').find("input[name='offsetY']").val();
			var imgWidth= $('#formEditCropsGrow').find("input[name='imgWidth']").val();
			var imgHeight = $('#formEditCropsGrow').find("input[name='imgHeight']").val();

			draggableImg.css("position","absolute");
			draggableImg.css("left", offsetX+"px");
			draggableImg.css("top", offsetY+"px");
			draggableImg.css("width", imgWidth);
			draggableImg.css("height", imgHeight);
		}
		
	    // 实时获取图片左上角顶点的相对位置(x, y)
	    
		function imagePositioneronDrag(e){
			var d = e.data;
			if (d.left < -$(d.parent).width()){d.left = -$(d.target).width()}
			if (d.top < 0){d.top = 0}
			if (d.left> $(d.parent).width()){
				d.left = $(d.parent).width() ;
			}
			if (d.top > $(d.parent).height()){
				d.top = $(d.parent).height();
			}
			offsetX.value = d.left;
			offsetY.value = d.top;		
			/* console.log("x:",d.left,"y:",d.top); */
		}
	    
		var draggableImg ;
		var imgExtData = {};
		$(document).ready(function(){
			draggableImg = $('#tools-imagePositioner-display img');
			draggableImg.draggable({
	            onStopDrag: function () {
	            	imgExtData.offsetX = draggableImg.position().left;
					imgExtData.offsetY = draggableImg.position().top;
					imgExtData.width = draggableImg.width();
					imgExtData.height = draggableImg.height();
					/* console.log("img是=");
	                console.log(imgExtData); */
	                
	                var row = {};
	    			row.offsetX = imgExtData.offsetX;
	    			row.offsetY = imgExtData.offsetY;
	    			row.imgWidth = imgExtData.width;
	    			row.imgHeight = imgExtData.height;
	    			$('#formEditCropsGrow').form('load', row);
	    			
	    			/* $('#formEditCropsGrow').find("input[name='offsetX']").val(imgExtData.offsetX);
	    	        $('#formEditCropsGrow').find("input[name='offsetY']").val(imgExtData.offsetY);
	    	        $('#formEditCropsGrow').find("input[name='imgWidth']").val(imgExtData.width);
	    	        $('#formEditCropsGrow').find("input[name='imgHeight']").val(imgExtData.height); */
	            }
	        });
			draggableImg.resizable();
		});
	    
		function positionerLoadImage(){
			draggableImg.css("position","absolute");
			draggableImg.css("left",imgExtData.offsetX+"px");
			draggableImg.css("top",imgExtData.offsetY+"px");
			draggableImg.css("width",imgExtData.width);
			draggableImg.css("height",imgExtData.height);
		}
		
		function gainPostion(){
			$('#positionDialog').dialog('close')
		}

	</script>
</body>
</html>